package city.spring.modules.material.controller;

import city.spring.modules.material.entity.MaterialQuantityEntity;
import city.spring.modules.material.service.MaterialQuantityService;
import city.spring.modules.material.vo.MaterialQuantityVO;
import city.spring.modules.material.vo.PrintMaterialQuantityVO;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.data.web.SortDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Controller：物资库存信息表
 *
 * @author 谢金婷
 * @date 2020-12-15 16:06:31
 */
@RestController
@RequestMapping("/material_quantity")
public class MaterialQuantityController extends ApiController {
    private final MaterialQuantityService materialQuantityService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<MaterialQuantityEntity, ?>> entityOrderFields;

    public MaterialQuantityController(MaterialQuantityService materialQuantityService) {
        this.materialQuantityService = materialQuantityService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(MaterialQuantityEntity::getId);
        entityOrderFields.add(MaterialQuantityEntity::getCategoryId);
        entityOrderFields.add(MaterialQuantityEntity::getMaterialId);
        entityOrderFields.add(MaterialQuantityEntity::getCode);
        entityOrderFields.add(MaterialQuantityEntity::getUnitmeasurement);
        entityOrderFields.add(MaterialQuantityEntity::getSpecifications);
        entityOrderFields.add(MaterialQuantityEntity::getUnitprice);
        entityOrderFields.add(MaterialQuantityEntity::getWarehousingquantity);
        entityOrderFields.add(MaterialQuantityEntity::getDeliveryquantity);
        entityOrderFields.add(MaterialQuantityEntity::getStorehouseId);
        entityOrderFields.add(MaterialQuantityEntity::getWarehousingInventoryAmount);
        entityOrderFields.add(MaterialQuantityEntity::getDeliveryInventoryAmount);
        entityOrderFields.add(MaterialQuantityEntity::getQuantity);
        entityOrderFields.add(MaterialQuantityEntity::getUpperWarningvalue);
        entityOrderFields.add(MaterialQuantityEntity::getLowerWarningvalue);
        entityOrderFields.add(MaterialQuantityEntity::getGmtCreate);
        entityOrderFields.add(MaterialQuantityEntity::getGmtModified);
    }

    /**
     * 获取全部的 <strong>物资库存信息表</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, MaterialQuantityEntity entity) {
        LambdaQueryChainWrapper<MaterialQuantityEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>物资库存信息表</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault @SortDefault.SortDefaults({@SortDefault(sort = "sname", direction = Sort.Direction.ASC), @SortDefault(sort = "name", direction = Sort.Direction.ASC)}) Pageable pageable, MaterialQuantityVO entity, Date[] warehousedate) {

        QueryWrapper<? extends MaterialQuantityEntity> queryWrapper = buildQuery(entity);
        if (warehousedate != null && warehousedate.length == 2) {
            queryWrapper.ge("t1.warehousedate", warehousedate[0]);
            queryWrapper.le("t1.warehousedate", warehousedate[1]);
        }
        return success(materialQuantityService.listPage(MyBatisUtils.toPage(pageable), queryWrapper));
    }

    /**
     * 获取一个 <strong>物资库存信息表</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {
        QueryWrapper<MaterialQuantityVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        List<MaterialQuantityVO> records = materialQuantityService.listPage(new Page<>(), wrapper).getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));

//        return success(materialQuantityService.getById(id));
    }

    /**
     * 添加一个 <strong>物资库存信息表</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping
    public Object add(@RequestBody MaterialQuantityEntity entity) {
        materialQuantityService.saveMaterialQuantity(entity);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 修改一个 <strong>物资库存信息表</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody MaterialQuantityEntity entity) {
        entity.setId(id);
        materialQuantityService.updateMaterialQuantity(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>物资库存信息表</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        materialQuantityService.deleteMaterialQuantity(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>物资库存信息表</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        materialQuantityService.deleteMaterialQuantity(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<MaterialQuantityEntity> buildLambdaQuery(MaterialQuantityEntity entity) {
        LambdaQueryChainWrapper<MaterialQuantityEntity> lambdaQuery = materialQuantityService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), MaterialQuantityEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getCategoryId()), MaterialQuantityEntity::getCategoryId, entity.getCategoryId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getMaterialId()), MaterialQuantityEntity::getMaterialId, entity.getMaterialId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getCode()), MaterialQuantityEntity::getCode, entity.getCode());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getUnitmeasurement()), MaterialQuantityEntity::getUnitmeasurement, entity.getUnitmeasurement());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getSpecifications()), MaterialQuantityEntity::getSpecifications, entity.getSpecifications());
        lambdaQuery.eq(entity.getUnitprice() != null, MaterialQuantityEntity::getUnitprice, entity.getUnitprice());
        lambdaQuery.eq(entity.getWarehousingquantity() != null, MaterialQuantityEntity::getWarehousingquantity, entity.getWarehousingquantity());
        lambdaQuery.eq(entity.getDeliveryquantity() != null, MaterialQuantityEntity::getDeliveryquantity, entity.getDeliveryquantity());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getStorehouseId()), MaterialQuantityEntity::getStorehouseId, entity.getStorehouseId());
        lambdaQuery.eq(entity.getWarehousingInventoryAmount() != null, MaterialQuantityEntity::getWarehousingInventoryAmount, entity.getWarehousingInventoryAmount());
        lambdaQuery.eq(entity.getDeliveryInventoryAmount() != null, MaterialQuantityEntity::getDeliveryInventoryAmount, entity.getDeliveryInventoryAmount());
        lambdaQuery.eq(entity.getQuantity() != null, MaterialQuantityEntity::getQuantity, entity.getQuantity());
        lambdaQuery.eq(entity.getUpperWarningvalue() != null, MaterialQuantityEntity::getUpperWarningvalue, entity.getUpperWarningvalue());
        lambdaQuery.eq(entity.getLowerWarningvalue() != null, MaterialQuantityEntity::getLowerWarningvalue, entity.getLowerWarningvalue());
        lambdaQuery.eq(entity.getGmtCreate() != null, MaterialQuantityEntity::getGmtCreate, entity.getGmtCreate());
        lambdaQuery.eq(entity.getGmtModified() != null, MaterialQuantityEntity::getGmtModified, entity.getGmtModified());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<MaterialQuantityEntity> buildQuery(MaterialQuantityVO entity) {
        QueryWrapper<MaterialQuantityEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "t1.id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getCategoryId()), "t1.category_id", entity.getCategoryId());
        wrapper.like(StringUtils.isNotBlank(entity.getCname()), "t2.cname", entity.getCname());
        wrapper.like(StringUtils.isNotBlank(entity.getMaterialId()), "t1.material_id", entity.getMaterialId());
        wrapper.like(StringUtils.isNotBlank(entity.getName()), "t3.name", entity.getName());
        wrapper.like(StringUtils.isNotBlank(entity.getCode()), "t1.code", entity.getCode());
        wrapper.like(StringUtils.isNotBlank(entity.getSuppliername()), "t4.suppliername", entity.getSuppliername());
        wrapper.like(StringUtils.isNotBlank(entity.getStorehouseId()), "t1.storehouse_id", entity.getStorehouseId());
        wrapper.like(StringUtils.isNotBlank(entity.getSname()), "t5.sname", entity.getSname());
        return wrapper;
    }

    /**
     * 根据storehouseId查找物资库存表 库存盘点使用
     *
     * @param storehouseId
     * @return
     */
    @GetMapping("/getMaterialByStorehouseId/{storehouseId}")
    public List<MaterialQuantityVO> getMaterialByStorehouseId(@PathVariable String storehouseId) {
        return materialQuantityService.getMaterialByStorehouseId(storehouseId);
    }

    @PostMapping("/getPrintMaterialQuantity")
    public Object getPrintMaterialQuantity(@RequestBody List<String> ids) {
        PrintMaterialQuantityVO data = materialQuantityService.getPrintMaterialQuantity(ids);
        return success(data);
    }

    /**
     * 根据仓库id查找物资（库存信息树形结构使用）
     *
     * @param pageable
     * @param entity
     * @param storehouseId
     * @return
     */
    @GetMapping("/getMaterialByStorehouseIdlist/{storehouseId}")
    public Object getMaterialByStorehouseIdlist(@PageableDefault Pageable pageable, MaterialQuantityVO entity, @PathVariable String storehouseId) {

        QueryWrapper<? extends MaterialQuantityEntity> queryWrapper = buildQueryByStorehouseId(entity);
        return success(materialQuantityService.materialByStorehouseIdlistPage(MyBatisUtils.toPage(pageable), queryWrapper, storehouseId));

    }

    private QueryWrapper<MaterialQuantityEntity> buildQueryByStorehouseId(MaterialQuantityVO entity) {
        QueryWrapper<MaterialQuantityEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "t1.id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getMaterialId()), "t1.material_id", entity.getMaterialId());
        wrapper.like(StringUtils.isNotBlank(entity.getName()), "t2.name", entity.getName());
        wrapper.like(StringUtils.isNotBlank(entity.getCode()), "t1.code", entity.getCode());
        wrapper.like(StringUtils.isNotBlank(entity.getStorehouseId()), "t1.storehouse_id", entity.getStorehouseId());
        wrapper.like(StringUtils.isNotBlank(entity.getSname()), "t3.sname", entity.getSname());
        return wrapper;
    }

    /**
     * 选择物资页面
     *
     * @param pageable
     * @param entity
     * @param warehousedate
     * @return
     */
    @GetMapping("/selectlistPage")
    public Object selectlistPage(@PageableDefault @SortDefault.SortDefaults({@SortDefault(sort = "sname", direction = Sort.Direction.ASC), @SortDefault(sort = "name", direction = Sort.Direction.ASC)}) Pageable pageable, MaterialQuantityVO entity, Date[] warehousedate) {

        QueryWrapper<? extends MaterialQuantityEntity> queryWrapper = buildQuery(entity);
        if (warehousedate != null && warehousedate.length == 2) {
            queryWrapper.ge("t1.warehousedate", warehousedate[0]);
            queryWrapper.le("t1.warehousedate", warehousedate[1]);
        }
        return success(materialQuantityService.selectlistPage(MyBatisUtils.toPage(pageable), queryWrapper));
    }
}
